package com.learn.service.impl;

import com.learn.mapper.LagouTokenMapper;
import com.learn.mapper.LagouUserMapper;
import com.learn.pojo.LagouUser;
import com.learn.service.AuthCodeService;
import com.learn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

/**
 * @program: learn-parent
 * @description
 * @author: luffy
 * @create: 2020-09-18 10:54
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private LagouUserMapper lagouUserMapper;
    @Autowired
    private LagouTokenMapper lagouTokenMapper;
    @Autowired
    private AuthCodeService authCodeService;
    @Override
    public boolean registry(String email, String password, String code, HttpServletResponse response) {
        Integer CodeStatus = authCodeService.validateAuthCode(email, code);
        if (CodeStatus == 0) {
            lagouUserMapper.addUser(email, password);
            String token = UUID.randomUUID().toString();
            lagouTokenMapper.addToken(email, token);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            return true;
        }else {
            return false;
        }

    }

    @Override
    public String login(String email, String password, HttpServletResponse response) {
        List<LagouUser> lagouUserList = lagouUserMapper.findLagouUser(email);

        if (!lagouUserList.isEmpty()) {
            LagouUser lagouUser = lagouUserList.get(0);
            if (password.equals(lagouUser.getPassword())) {
                String token = UUID.randomUUID().toString();
                Cookie cookie = new Cookie("token", token);
                cookie.setPath("/");
                lagouTokenMapper.addToken(email, token);
                return lagouUser.getEmail();
            }else{
                System.out.println("密码错误");
                return "密码错误";
            }
        }else{
            System.out.println("邮箱不存在");
            return "邮箱不存在";
        }
    }
}
